<style rel="stylesheet/scss" lang="scss" scoped>
.dashboard-editor-container {
  padding: 18px 22px 22px 22px;
  background-color: rgb(240, 242, 245);
  margin-bottom: 80px;

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

.form-operator-button {
  background-color: #fff;
  position: fixed;
  width: 100%;
  left: 0px;
  right: 0;
  bottom: 33px;
  height: 64px;
  line-height: 64px;
  text-align: right;
  box-shadow: 0 -1px 2px 0 rgba(0, 0, 0, 0.05);
  z-index: 10;
}

.form-el-radion {
  line-height: 30px;
  padding: 5px 0px;
  width: 100%;
}

.hex-form-inf {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  cursor: pointer;
  margin-right: 40px;
  position: relative;
  min-height: 33px;
  margin-left: 60px;
  line-height: 33px;
}

.hex-form-inf-content {
  font-size: 14px;
  font-weight: 500;
  display: none;
}

.hex-form-inf-icon {
  font-size: 20px;
  margin-top: 5px;
  position: absolute;
  right: 0px;
}
</style>
<template>
  <div class="dashboard-container">
    <div class="dashboard-editor-container" v-if="!lookPeriodJobDetailFlag">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>周期作业实例列表</span>
        </div>
        <!--工具栏-->
        <div class="head-container">
          <crudOperation :permission="permission" :moreQueryList="moreQueryList"/>
        </div>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading" :data="crud.data" row-key="id" @select="crud.selectChange"
                  @select-all="crud.selectAllChange" @selection-change="crud.selectionChangeHandler"
                  @filter-change="crud.handleFilterChange"
                  @row-dblclick="goTaskInfo" @cell-mouse-enter="showTooltip" @cell-mouse-leave="hideTooltip"
                  :row-style="{ cursor: 'pointer'}"
                  :header-cell-style="{ background: 'rgba(52, 125, 225, 0.1)', color: '#404248' }" border stripe>
          <el-table-column type="selection"/>
          <el-table-column v-if="columns.visible('bizDate')" :show-overflow-tooltip="true" label="业务日期" prop="bizDate"
                           min-width="150">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              <span style="margin-left: 10px">{{ scope.row.bizDate }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="columns.visible('jobCode')" :show-overflow-tooltip="true" label="作业编码" prop="jobCode"
                           min-width="200"/>
          <el-table-column v-if="columns.visible('jobName')" :show-overflow-tooltip="true" label="作业名称" prop="jobName"
                           min-width="200"/>
          <el-table-column v-if="columns.visible('labelName')" :show-overflow-tooltip="true" label="标签名称"
                           prop="labelName"/>
          <!--          :formatter="jobStatusFormatter" :filters="jobStatusDict"-->
          <el-table-column v-if="columns.visible('jobStatus')" prop="jobStatus" label="状态"
                           min-width="100" key="jobStatus" filter-placement="bottom-end" :filter-multiple="false"
                           column-key="jobStatus">
            <template slot-scope="scope">
              <!-- <el-tag type="success" v-for="(item,i) in jobStatusDict"></el-tag> v-for="(item,key,i) in jobStatusDict"-->
              <el-tag size="medium" :type="formatterJobStatusType(scope.row.jobStatus)">
                {{ formatterJobStatus(scope.row.jobStatus) }}
                <!--{{item}}-&#45;&#45;{{key}}-->
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="columns.visible('taskStatusCount')" align="center" min-width="100"
                           :show-overflow-tooltip="true" label="任务统计" prop="taskStatusCount">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>待执行 执行中 暂停中 | 执行成功 置虚 | 执行失败</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium">{{ scope.row.taskStatusCount }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column v-if="columns.visible('sortNo')" align="center" min-width="100" :show-overflow-tooltip="true"
                           label="优先级" prop="sortNo"/>
          <el-table-column v-if="columns.visible('upTs')" align="center" min-width="160" :show-overflow-tooltip="true"
                           label="更新时间" prop="upTs"/>
          <el-table-column v-if="columns.visible('crtTs')" align="center" min-width="160" :show-overflow-tooltip="true"
                           label="创建时间" prop="crtTs"/>
        </el-table>
      </el-card>
      <!--修改-->
      <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU"
                 :visible.sync="crud.status.cu > 0"
                 :title="crud.status.title" width="480px">
        <el-form ref="form" :inline="true" :model="form" size="small" label-width="160px">
          <el-row v-if="crud.editType.changeBizDate">
            <el-col :span="24">
              <el-form-item label="业务日期">
                <el-date-picker v-model="form.bizDate" type="date" placeholder="选择日期" value-format="yyyyMMdd">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="crud.editType.changeStatus">
            <el-col :span="24">
              <el-form-item label="运行状态">
                <el-select v-model="form.editJobStatus" filterable placeholder="请选择">
                  <el-option v-for="item in editJobStatusOptions" :key="item.value" :label="item.label"
                             :value="item.value"
                             :disabled="item.disabled">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button icon="el-icon-document-delete" @click="crud.cancelCU">取消</el-button>
          <el-button icon="el-icon-document-add" :loading="crud.status.cu === 2" type="primary" @click="submitCU">保存
          </el-button>
        </div>
      </el-dialog>
      <!-- 批量复制 -->
      <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU"
                 :visible.sync="crud.status.copy > 0"
                 :title="crud.status.title" width="680px">
        <el-form ref="form" :inline="true" :model="form" size="small" label-width="160px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="作业状态" prop="jobCopyStatus">
                <el-select v-model="form.jobCopyStatus" filterable placeholder="请选择" @change="jobCopyStatusChange">
                  <el-option v-for="item in this.dict.cycle_job_status" :key="item.value" :label="item.label"
                             :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="业务日期">
                <el-date-picker v-model="form.bizDates" type="daterange" range-separator="至" value-format="yyyy-MM-dd"
                                start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button icon="el-icon-document-delete" @click="crud.cancelCU">取消</el-button>
          <el-button icon="el-icon-document-add" :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">
            保存
          </el-button>
        </div>
      </el-dialog>
    </div>
    <detail v-if="lookPeriodJobDetailFlag" v-model="lookPeriodJobDetailFlag" :pk-id="lookPeriodJob.pkId"
            :job-code="lookPeriodJob.jobCode" :biz-date="lookPeriodJob.bizDate"/>
  </div>
</template>

<script>
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import crudOperation from '@crud/extend/cycleTask/cycleJob/app/CRUD.operation'
import job from '@/api/cycleJob/job'
import {MessageBox} from 'element-ui'
import config from '@/settings'
import Detail from './detail'

const isDefBizDate = config.isDefBizDate
const dateOffset = config.dateOffset
// crud交由presenter持有
const queryList = [{
  cloumValue: 'jobName',
  cloumName: '作业名称'
},
  {
    cloumValue: 'jobCode',
    cloumName: '作业编码'
  },
  {
    cloumValue: 'labelName',
    cloumName: '标签名称'
  },
  {
    cloumValue: 'bizDate',
    cloumName: '业务日期'
  }
]
const defaultCrud = CRUD({
  title: '作业实例',
  url: 'api/periodJob',
  query: {
    jobCode: null,
    jobName: null,
    bizDate: null,
    jobStatus: null,
    bizDateType: null,
    startTime: [],
    endTime: []
  },
  crudMethod: {
    ...job
  },
  queryOnPresenterCreated: false,
  optShow: {
    add: false,
    edit: true,
    del: true,
    download: true,
    batchUpdateStatus: true,
    batchUpdateBizDate: true,
    cpJob: true,
    proCompleted: false,
    proFailed: false
  }
})
const defaultForm = {
  editJobStatus: null,
  editBizDate: null,
  jobCopyStatus: '1'
}
export default {
  name: 'appJob',
  components: {crudOperation, Detail},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['cycle_job_status', 'job_def_status'],
  filters: {
    formatTime: function (value) {
      if (value != '') {
        return value.slice(0, 19).replace('T', ' ')
      }
    }
  },
  data() {
    return {
      menus: [],
      active: 0,
      dataList: [],
      taskDataList: [],
      taskForm: {
        taskCode: '',
        taskName: '',
        shellPath: '',
        shellParam: '',
        weight: '',
        errCount: '',
        isEndTask: true,
        isOrder: true
      },
      moreQueryList: [
        {
          cloumLable: 'jobCodeFuzzy',
          name: '作业编码',
          type: 'textarea',
          placeholder: '请输入作业编码，支持单个模糊查询和批量精确查询用逗号分割',
          defaultValue: null
        },
        {
          cloumLable: 'jobNameFuzzy',
          name: '作业名称',
          type: 'textarea',
          placeholder: '请输入作业名称，支持单个模糊查询和批量精确查询使用逗号分割',
          defaultValue: null
        },
        {
          cloumLable: 'labelName',
          name: '标签名称',
          type: 'input',
          placeholder: '请输入标签名称',
          defaultValue: null
        },
        {
          cloumLable: 'jobStatus',
          name: '作业状态',
          type: 'radio',
          placeholder: '',
          defaultValue: null,
          radioList: [{
            label: '',
            value: '全部'
          },
            {
              label: '1',
              value: '未完成'
            },
            {
              label: '4',
              value: '已完成'
            },
          ]
        },
        {
          cloumLable: 'bz',
          cloumLableType: 'bzType',
          name: '业务日期',
          type: 'dateNoTimePicker',
          placeholder: '',
          defaultValue: null
        },
        {
          cloumLable: 'startTime',
          cloumLableType: 'startTimeType',
          name: '开始时间',
          type: 'timeFramePicker',
          placeholder: '',
          defaultValue: null
        },
        {
          cloumLable: 'endTime',
          cloumLableType: 'endTimeType',
          name: '结束时间',
          type: 'timeFramePicker',
          placeholder: '',
          defaultValue: null
        }
      ],
      permission: {
        del: ['appJob:del'],
        edit: ['appJob:edit'],
        copy: ['appJob:copy'],
        rerun: ['appJob:rerun']
      },
      isBaskUps: true,
      jobDict: [],
      jobStatusDict: [],
      editJobStatusOptions: [],
      lookPeriodJob: null,
      lookPeriodJobDetailFlag: false
    }
  },
  created() {
    this.active = 0
    this.crud.query.bizDate = this.currentDate()
    this.initData()
    this.jobDict = this.dict.cycle_job_status
  },
  watch: {
    jobDict() {
      this.$nextTick(() => {
        this.jobDict.forEach(item => {
          var obj = {
            text: item.label,
            value: item.value
          }
          this.jobStatusDict.push(obj);
          var option = {
            label: item.label,
            value: item.value
          }
          if (item.value == "2" || item.value == "5") {
            option.disabled = true
          }
          this.editJobStatusOptions.push(option);
        })
      })
    }
  },
  methods: {
    jobCopyStatusChange(val) {
      return this.dict.label.cycle_job_status[val]
    },
    formatterjobName(val) {
      return val.jobName + "(" + val.jobCode + ")"
    },
    currentDate() {
      let timestamp = Date.now() + dateOffset * 1000 * 60 * 60 * 24
      let date = new Date(timestamp)
      let year = date.getFullYear()
      let month = ('0' + (date.getMonth() + 1)).slice(-2)
      let sdate = ('0' + date.getDate()).slice(-2)
      let result = year + month + sdate
      return result
    },
    //复制前处理
    [CRUD.HOOK.beforeToCopy](crud) {
      return this.checkedBizDate(crud.form.copyObject)
    },
    //复制提交前校验
    [CRUD.HOOK.beforeValidateCU](crud) {
      return this.checkedBizDateIsNull(crud.form)
    },
    //修改完成后
    [CRUD.HOOK.afterSubmit](crud) {
      this.crud.editType.changeStatus = false
      this.crud.editType.changeBizDate = false
    },
    [CRUD.HOOK.beforeToEdit](crud, form) {
      form.editBizDate = form.bizDate
      form.editJobStatus = form.jobStatus
    },
    submitCU() {
      if (this.crud.editType.changeStatus == true && this.crud.editType.changeBizDate == true) {
        this.crud.submitCU()
      } else if (this.crud.editType.changeStatus == true && this.crud.editType.changeBizDate == false) {
        this.batchChangeStatus()
      } else if (this.crud.editType.changeStatus == false && this.crud.editType.changeBizDate == true) {
        this.batchChangeBizDate()
      }
    },
    batchChangeStatus() {
      this.crud.status.edit = CRUD.STATUS.PROCESSING
      let formData = {
        periodJobList: this.crud.form.selections,
        jobStatus: this.crud.form.editJobStatus
      }
      job.batchChangeStatus(formData)
        .then((res) => {
          this.crud.status.edit = CRUD.STATUS.NORMAL
          this.crud.editType.changeStatus = false
          this.crud.resetForm()
          this.crud.refresh()
          let msg = '更新【' + res.upCount + '】个作业,成功【' + res.successCount + '】个！'
          this.crud.notify(msg, CRUD.NOTIFICATION_TYPE.SUCCESS)
        })
        .catch(() => {
          this.crud.status.edit = CRUD.STATUS.PREPARED
        })
    },
    batchChangeBizDate() {
      this.crud.status.edit = CRUD.STATUS.PROCESSING
      let pkIds = []
      this.crud.form.selections.forEach(item => {
        pkIds.push(item.pkId)
      })
      let formData = {
        pkIds: pkIds,
        bizDate: this.crud.form.bizDate
      }
      job.batchChangeBizDate(formData)
        .then(() => {
          this.crud.status.edit = CRUD.STATUS.NORMAL
          this.crud.editType.changeBizDate = false
          this.crud.resetForm()
          this.crud.refresh()
        })
        .catch(() => {
          this.crud.status.edit = CRUD.STATUS.PREPARED
        })
    },
    checkedBizDate(data) {
      let bizDate = data[0].bizDate
      for (let i = 0; i < data.length; i++) {
        if (bizDate != data[i].bizDate) {
          MessageBox.alert(`请选中相同业务日期的多条记录!`, '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          return false
        }
      }
      return true
    },
    checkedBizDateIsNull(data) {
      if (data.bizDates !== null) {
        return true
      } else {
        MessageBox.alert(`请选择起始日期!`, '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        })
        return false
      }
    },
    //进入时显示提示框
    showTooltip(row) {
      //需要显示浮框的条件
      //if (row.filterFlag) {
      row.showTooltip = true
      //}
    },
    //退出时隐藏提示框
    hideTooltip(row) {
      row.showTooltip = false
    },
    initData() {
      //跳转时的当前页 在main.js的全局变量
      let p = this.$root.p
      //alert(p);
      if (p != 1) {
        this.crud.pageChangeHandler(p)
        this.$root.p = 1
      } else {
        this.crud.toQuery()
      }
    },
    jobStatusFormatter(row, column) {
    },
    formatterJobStatusType(val) {
      const type = ['', 'info', 'primary', 'warning', 'success', 'danger']
      return type[val]
    },
    formatterJobStatus(val) {
      return this.dict.label.cycle_job_status[val]
    },
    goTaskInfo(row, column, event) {
      this.lookPeriodJob = row
      this.lookPeriodJobDetailFlag = true
    }
  }
}
</script>
